package com.loveyukari.service;


import com.loveyukari.dao.ShieldAuthDao;
import com.loveyukari.model.ShieldAuth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

@Service
public class ShieldAuthService {

    @Autowired
    private ShieldAuthDao shieldAuthDao;

    @Autowired
    private RedisService redisService;

    private String SHIELD_AUTH_KEY = "shield:auth:";

    public void add(Integer authId,Date endDate){
        ShieldAuth shieldAuth = shieldAuthDao.select(authId);
        if (shieldAuth == null){
            shieldAuth= new ShieldAuth();
            shieldAuth.setAuthId(authId);
            shieldAuth.setEndDate(endDate);
            shieldAuthDao.insert(shieldAuth);
            reload(authId);
        } else {
            shieldAuthDao.delete(shieldAuth.getId());
            add(authId,endDate);
        }
    }

    public boolean isShieldAuth(Integer authId){
        String key = SHIELD_AUTH_KEY+authId;
        ShieldAuth shieldAuth = redisService.get(key, ShieldAuth.class);
        if (shieldAuth == null){
            return false;
        }
        if (new Date().getTime() >= shieldAuth.getEndDate().getTime()){
            reload(authId);
            return false;
        } else {
            return true;
        }
    }



    public void reload(Integer authId){
        String key = SHIELD_AUTH_KEY+authId;
        ShieldAuth shieldAuth = shieldAuthDao.select(authId);
        if (new Date().getTime() >= shieldAuth.getEndDate().getTime()){
            redisService.del(key);
            shieldAuthDao.delete(shieldAuth.getId());
        } else {
            redisService.set(key,shieldAuth);
        }

    }

    @PostConstruct
    public void reloadAll(){
        List<ShieldAuth> shieldAuths = shieldAuthDao.selectAll();
        long now = new Date().getTime();
        Set<String> keys = redisService.keys(SHIELD_AUTH_KEY + "*");
        redisService.del(keys);
        for (ShieldAuth shieldAuth:
             shieldAuths) {
            if (now >= shieldAuth.getEndDate().getTime()){
                shieldAuthDao.delete(shieldAuth.getId());
            } else {
                redisService.set(SHIELD_AUTH_KEY+shieldAuth.getAuthId(),shieldAuth);
            }
        }
    }
}
